<template>
  <div id="login">
    <div class="login-wrap">
      <ul class="menu-tab">
        <li
          v-for="(item, index) in menuTab"
          :key="index"
          :class="{ current: item.current }"
          @click="toggleMenu(item)"
        >
          {{ item.text }}
        </li>
      </ul>
      <!--表单 start-->
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="login-form"
        size="medium"
        label-position="top"
      >
        <el-form-item label="用户名" prop="username" class="item-form">
          <el-input type="text" v-model="ruleForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" class="item-form">
          <el-input
            type="password"
            v-model="ruleForm.password"
            autocomplete="off"
            minlength="6"
            maxlength="20"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="重复密码"
          prop="repassword"
          class="item-form"
          v-if="model === 'register'"
        >
          <el-input
            type="password"
            v-model="ruleForm.repassword"
            autocomplete="off"
            minlength="6"
            maxlength="20"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱验证码" prop="email" class="item-form">
          <el-row :gutter="10">
            <el-col :span="15">
              <el-input v-model="ruleForm.email" minlength="6" maxlength="6"></el-input>
            </el-col>
            <el-col :span="9">
              <el-button
                type="success"
                class="block"
                @click="getEmail()"
                :disabled="codeButtonStatus.status"
              >{{ codeButtonStatus.text }}</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="图形验证码" prop="captcha" class="item-form">
          <el-row :gutter="10">
            <el-col :span="15">
              <el-input v-model="ruleForm.captcha.code" minlength="4" maxlength="4"></el-input>
            </el-col>
            <el-col :span="9">
              <img :src="ruleForm.captcha.src" style="height:36px;width:100%;" @click="fetchCaptcha">
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-button
            type="danger"
            @click="submitForm('ruleForm')"
            class="login-btn block"
            :disabled="loginButtonStatus"
          >
            {{ model === "login" ? "登录" : "注册" }}
          </el-button>
        </el-form-item>
      </el-form>
      <!--表单 end-->
    </div>
  </div>
</template>

<script>
  import {
    stripscript /*,validateEmail,validatePassword*/,
    validateCode
  } from "../../utils/validate";
  import { reactive, ref, onMounted} from "@vue/composition-api";
  import { GetEmail, Register, Login, GetCaptcha} from "../../api/login";
  import sha1 from 'js-sha1';

  export default {
    name: "login",
    setup(pops, context) {
      /** === === === === === === 函数声明 === === === === === ===*/
      //#region
      const toggleMenu = data => {
          menuTab.forEach(item => {
            item.current = false;
          });
          data.current = true;
          model.value = data.type;
          clearFormData();
          //重置表单
          clearCountDown();
        };
      // 提交表单
      const submitForm = formName => {
        context.refs[formName].validate(valid => {
          // 表单验证通过
          if (valid) {
            if(model.value === "login"){
              login()
            }else {
              register()
            }

          } else {
            console.log("error submit!!");
            return false;
          }
        });
      };
      // 注册
      const register = () => {
        return context.root.$message("暂不开放");
        /*const requestData = {
          username: ruleForm.username,
          // password: ruleForm.password
          password: sha1(ruleForm.password)
          // ,email: ruleForm.email
        };
        Register(requestData).then(res => {
          const data = res.data;
          context.root.$message({
            message: data.message,
            type: "success"
          });

          // 注册成功自动跳转到登录
          toggleMenu(menuTab[0]);
          return false;
        }).catch(error => {
          context.root.$message({
            message: error,
            type: "fail"
          })
        });*/
      };
      // 登录
      const login = () => {
        const requestData = {
          username: ruleForm.username,
          password: ruleForm.password,
          captchaId: ruleForm.captcha.id,
          verifyCode: ruleForm.captcha.code
          // ,password: sha1(ruleForm.password) // 前端加密作用不大 后端还要加一道
          // ,email: ruleForm.email
        };

        context.root.$store.dispatch("app/login",requestData).then(res => {
          context.root.$router.push({
            name: "Home"
            // ,params:{
            //   id:""
            //   //...
            // }
          });
        })
      };
      // 清除表单字段数据
      const clearFormData = () => {
        context.refs.ruleForm.resetFields();
      };
      // 清除倒计时
      const clearCountDown = () => {
        updateButtonStatus({status: false, text: "获取验证码"});
        clearInterval(timer.value);
      };
      // 更新按钮状态
      const updateButtonStatus = (params) => {
        codeButtonStatus.status = params.status;
        codeButtonStatus.text = params.text;
      };
      // 获取验证码
      const getEmail = () => {
        if (ruleForm.username == "") {
          context.root.$message.error("用户名不能为空!");
          return false;
        }

        /*if(!validateEmail(ruleForm.username)){
          context.root.$message.error("邮箱格式有误,请重新输入!!");
          return false
        }*/
        updateButtonStatus({status: true, text: "发送中"});

        GetEmail({ username: ruleForm.username, module: "login" })
          .then(data => {
            context.root.$message({
              message: data.msg || "已发送,请注意查收~",
              type: "success"
            });
            // 启用登录或注册按钮
            loginButtonStatus.value = false;
            countDown(60);
          })
          .catch(error => {
            console.log(error);
          });
      };
      // 倒计时
      const countDown = number => {
        if(timer.value) clearInterval(timer.value);

        timer.value = setInterval(() => {
          number--;
          if (number === 0) {
            clearInterval(timer.value);
            updateButtonStatus({status: false, text: "获取验证码"});
          } else {
            codeButtonStatus.text = `倒计时${number}秒`;
          }
        }, 1000);
      };
      // 验证用户名
      const checkUsername = (rule, value, callback) => {
        value = stripscript(value);
        ruleForm.username = value;

        if (value === "") {
          callback(new Error("请输入用户名"));
        } /*else if (!validateEmail(value)) {
        callback(new Error('用户名格式有误'));
      } */ else {
          callback();
        }
      };
      // 验证密码
      const checkPassword = (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请输入密码"));
        } /*else if (!validatePassword(value)) {
        callback(new Error("密码为6至20位的数字字母"));
      } */ else {
          callback();
        }
      };
      // 验证重复密码
      const checkRePassword = (rule, value, callback) => {
        if (model.value === "login") return callback();
        if (value === "") {
          callback(new Error("请再次输入密码!"));
        } else if (value !== ruleForm.password) {
          callback(new Error("两次密码输入不一致!"));
        } else {
          callback();
        }
      };
      // 验证验证码
      const checkCode = (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请输入验证码"));
        } else if (!validateCode(value)) {
          callback(new Error("验证码格式有误"));
        } else {
          callback();
        }
      };
      // 获取图形验证码
      const fetchCaptcha = async () => {
        try {
          const result = await GetCaptcha();
          ruleForm.captcha.src = result.url;
          ruleForm.captcha.id = result.captchaId;
        } catch (e) {
          console.error('something wrong with init captcha data')
        }
      };
      //#endregion

      /** === === === === === === 数据声明 === === === === === ===*/
      //#region
      // 存放倒计时timerID
      const timer = ref(null);
      //
      const menuTab = reactive([
        { text: "登录", current: true, type: "login" },
        { text: "注册", current: false, type: "register" }
      ]);
      // console.log("menuTab:", menuTab);
      // 登录还是注册
      const model = ref("login");
      // 登录按钮禁用状态
      const loginButtonStatus = ref(true);
      // 验证码按钮状态
      const codeButtonStatus = reactive({
        status: false,
        text: "获取验证码"
      });
      // 表单绑定数据
      const ruleForm = reactive({
        username: "",
        password: "",
        // email 验证码
        email: "",
        repassword: "",
        // 图形验证码
        captcha: {
          src: "",
          id: "",
          code: ""
        }
      });
      // 表单验证会用到的辅助数据
      const rules = reactive({
        username: [{ validator: checkUsername, trigger: "blur" }],
        password: [{ validator: checkPassword, trigger: "blur" }],
        repassword: [{ validator: checkRePassword, trigger: "blur" }],
        email: [{ validator: checkCode, trigger: "blur" }]
      });
      //#endregion

      /** === === === === === === 生命周期 === === === === === ===*/
      onMounted(()=>{
        fetchCaptcha();
      });

      /** ↓模板里要用的*/
      return {
        menuTab,
        model,
        rules,
        ruleForm,
        loginButtonStatus,
        codeButtonStatus,
        toggleMenu,
        submitForm,
        getEmail,
        fetchCaptcha
      };
    }
  };
</script>

<style lang="scss" scoped>
  #login {
    height: 100vh;
    background-color: #344a5f;
  }
  .login-wrap {
    width: 330px;
    margin: auto;
    overflow: hidden;
  }
  .menu-tab {
    text-align: center;
    li {
      display: inline-block;
      width: 88px;
      line-height: 36px;
      font-size: 14px;
      color: #fff;
      border-radius: 2px;
      cursor: pointer;
    }
    .current {
      background: rgba(0, 0, 0, 0.1);
    }
  }
  .login-form {
    /deep/ label {
      color: #fff;
      font-size: 14px;
      display: block;
    }
    .item-form {
      margin-bottom: 13px;
    }
    .block {
      display: block;
      width: 100%;
    }
    .login-btn {
      margin-top: 19px;
    }
  }
</style>
